package com.yoo.ons.function.album

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import com.yoo.chat.kit.utils.KitStorageUtils
import com.yoo.chat.kit.utils.videocompressor.VideoCompress
import com.yoo.module_base.utils.MD5Util
import com.yoo.module_base.utils.StatusBarUtil
import com.yoo.ons.ToastUtil.showToast
import com.yoo.ons.adapter.PersonAlbumAdapter
import com.yoo.ons.base.BaseVMActivity
import com.yoo.ons.base.HttpRequestListener
import com.yoo.ons.databinding.DialogFragmentPersonAlbumBinding
import com.yoo.ons.function.album.viewmodel.PersonAlbumViewModel
import com.yoo.ons.model.PictureManagerModel
import com.yoo.ons.util.UploadPhotoUtil
import java.io.File

class PersonAlbumActivity : BaseVMActivity<DialogFragmentPersonAlbumBinding, PersonAlbumViewModel>(
    DialogFragmentPersonAlbumBinding::inflate,
    PersonAlbumViewModel::class.java
) {
    private val personAlbumAdapter by lazy {
        PersonAlbumAdapter(this)
    }
    override fun initView() {
        super.initView()
        binding.titleBar.setPadding(0, StatusBarUtil.getStatusBarHeight(this), 0, 0)
        binding.titleBar.setBackListener {
            finish()
        }
        binding.titleBar.setTitleText("Private Album")
    }

    override fun initData() {
        //判断是否会员
        val member = intent.getBooleanExtra("member", false)
        binding.noPersonAlbumContainer.isVisible = !member
        binding.personAlbumList.isVisible = member
        if (member) {
            mViewModel?.getPersonAlbum()
            binding.personAlbumList.layoutManager = GridLayoutManager(this, 3)
            binding.personAlbumList.adapter = personAlbumAdapter
            mViewModel?.personAlbumLiveData?.observe(this) {
                if (it?.images != null) {
                    personAlbumAdapter.setDataList(it.images)
                }
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    val selectList = PictureSelector.obtainSelectorList(data)
                    addImage(selectList)
                }
            }
        }
    }

    private fun addImage(selectList: ArrayList<LocalMedia>?) {
        selectList?.forEach {
            val path = when {
                it.isCompressed -> {
                    it.compressPath
                }

                it.isCut -> {
                    it.cutPath
                }

                else -> {
                    it.realPath
                }
            }
            if (path.contains(".mp4", true) || it.mimeType.contains(
                    ".3gp",
                    true
                ) || it.mimeType.contains(".mov", true)
            ) {
                if (it.duration > 60 * 1000) {
                    showToast(getString(com.yoo.module_res.R.string.video_too_overlong_tip))
                    return
                }
                if (it.duration < 1000) {
                    showToast(getString(com.yoo.module_res.R.string.video_too_short_tip))
                    return
                }

                if (it.size > 50 * 1024 * 1024) {
                    showToast(getString(com.yoo.module_res.R.string.video_too_big_tip))
                    return
                }
                var suffix="mp4"
                if (it.mimeType.contains("/")){
                    suffix = it.mimeType.substring(it.mimeType.lastIndexOf("/") + 1)
                }

                val compressPath = KitStorageUtils.getImageSavePath(this) +
                        File.separator+"${MD5Util.getMD5(System.currentTimeMillis().toString())}.$suffix"

                VideoCompress.compressVideo(
                    this,
                    path, compressPath, object : VideoCompress.CompressListener {
                        override fun onStart() {}
                        override fun onSuccess() {
                            val imagesBean = PictureManagerModel("","","",true)
                            addPhoto(imagesBean)
                            UploadPhotoUtil.uploadFile(this@PersonAlbumActivity,compressPath, it.mimeType, object : UploadPhotoUtil.OnListener {
                                override fun onSuccess(successPath: String,imageCode:String) {
                                    saveAlbums(successPath, it.duration)
                                }

                                override fun fail() {
                                    showToast("upload error,pls try again")
                                }

                            })
                        }

                        override fun onFail() {
                        }

                        override fun onProgress(percent: Float) {
                        }
                    })
            } else {
                val imagesBean = PictureManagerModel("","","",true)
                addPhoto(imagesBean)
                UploadPhotoUtil.uploadFile(this,path, it.mimeType, object : UploadPhotoUtil.OnListener {
                    override fun onSuccess(successPath: String,imageCode:String) {
                        saveAlbums(successPath, it.duration)
                    }

                    override fun fail() {
                        showToast("Upload failed")
                    }

                })
            }
        }
    }

    private fun saveAlbums(successPath: String, duration: Long) {
        mViewModel?.getPersonAlbumAdd(object :HttpRequestListener<PictureManagerModel>(){
            override fun addRequestParams(params: HashMap<String, Any>) {
                params["imageUrl"]= successPath
                params["type"]= 3
                params["videoLength"]= duration
            }

            override fun success(t: PictureManagerModel?) {
                t?.apply {
                    var lastPosition = 0
                    for (i in 0 until personAlbumAdapter.getDataList().size) {
                        if (personAlbumAdapter.getDataList()[i].loading) {
                            lastPosition = i
                        }
                    }
                    personAlbumAdapter.getDataList()[lastPosition].imageUrl = t.imageUrl
                    personAlbumAdapter.getDataList()[lastPosition].imageCode = t.imageCode
                    personAlbumAdapter.getDataList()[lastPosition].videoLength = t.videoLength
                    personAlbumAdapter.getDataList()[lastPosition].loading = false
                    personAlbumAdapter.notifyDataSetChanged()
                }
            }

        })
    }

    fun addPhoto(bean: PictureManagerModel) {
        personAlbumAdapter.getDataList().add(1, bean)
        personAlbumAdapter.notifyDataSetChanged()
    }

    companion object{
        /**
         * member 是否会员
         * pbSize 个人相册数量
         */
        fun start(context: Context?,member:Boolean,pbSize:Int){
            val intent = Intent(context, PersonAlbumActivity::class.java)
            intent.putExtra("member",member)
            intent.putExtra("pbSize",pbSize)
            context?.startActivity(intent)
        }
    }
}